import {
    Breadcrumb, Row, Col, Button, Form, Input, message, Upload, Modal, Select, Radio, DatePicker, Space
} from 'antd';
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons';
import './index.css'
import 'moment/locale/zh-cn';
import moment from 'moment';

import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router';

import { typeGoods, addGoods } from '../../../../api/WL/goods'

const AddGoods = () => {
    const navigate = useNavigate();
    const [type, setType] = useState([]);
    const [color1, setColor1] = useState('红色')
    const [size1, setSize1] = useState('L')

    const [time, setTime] = useState('');

    useEffect(() => {
        typeGoods().then((res) => {
            console.log(res);
            setType(res.data)
        })
    }, [])

    const [form1] = Form.useForm();
    const [form2] = Form.useForm();
    const [form3] = Form.useForm();

    //第一个表单的图片上传
    const getBase64 = (img, callback) => {
        const reader = new FileReader();
        reader.addEventListener('load', () => callback(reader.result));
        reader.readAsDataURL(img);
    };

    const beforeUpload = (file) => {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';

        if (!isJpgOrPng) {
            message.error('You can only upload JPG/PNG file!');
        }

        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isLt2M) {
            message.error('Image must smaller than 2MB!');
        }

        return isJpgOrPng && isLt2M;
    };
    const [loading, setLoading] = useState(false);
    const [imageUrl, setImageUrl] = useState();
    const [src, setSrc] = useState();

    const handleChange = (info) => {

        if (info.file.status === 'uploading') {
            setLoading(true);
            return;
        }

        if (info.file.status === 'done') {
            // Get this url from response in real world.
            console.log(info.file);
            setSrc(info.file.response.fileName);

            getBase64(info.file.originFileObj, (url) => {
                setLoading(false);
                setImageUrl(url);
            });
        }
    };

    const uploadButton = (
        <div>
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div
                style={{
                    marginTop: 8,
                }}
            >
                Upload
            </div>
        </div>
    );

    //第一个表单图片轮播图的上传
    const getBase642 = (file) =>
        new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.readAsDataURL(file);

            reader.onload = () => resolve(reader.result);

            reader.onerror = (error) => reject(error);
        });
    const [previewVisible, setPreviewVisible] = useState(false);
    const [previewImage, setPreviewImage] = useState('');
    const [previewTitle, setPreviewTitle] = useState('');
    const [fileList, setFileList] = useState([]);

    const handleCancel = () => setPreviewVisible(false);

    const handlePreview = async (file) => {
        if (!file.url && !file.preview) {
            file.preview = await getBase642(file.originFileObj);
        }

        setPreviewImage(file.url || file.preview);
        setPreviewVisible(true);
        setPreviewTitle(file.name || file.url.substring(file.url.lastIndexOf('/') + 1));
    };

    const handleChange2 = ({ fileList: newFileList }) => {
        console.log(newFileList);

        return setFileList(newFileList)
    };

    const uploadButton2 = (
        <div>
            <PlusOutlined />
            <div
                style={{
                    marginTop: 8,
                }}
            >
                Upload
            </div>
        </div>
    );
    //第一个表单的下拉列表渲染
    const selectListRender = (arr) => {
        let list = []
        arr.map((v, i) => list.push(<Select.Option value={v.classId}>{v.calssName}</Select.Option>))
        return list
    }

    //第二个表单的颜色选择
    const btnList = [
        { status: 0, name: '红色' },
        { status: 1, name: '绿色' },
        { status: 2, name: '蓝色' },
    ]
    const [isTopBtn, setIsTopBtn] = useState(0)
    const clickTopBtn = (value) => {
        setIsTopBtn(value)
    }

    const colorSelect = (value) => {
        setColor1(value.name);
        return clickTopBtn(value.status)

    }
    const btnListRender = (arr) => {
        let list = []
        arr.map((v, i) => list.push(<Button style={{ marginRight: '10px', width: '60px' }} type={v.status === isTopBtn ? 'primary' : 'default'} key={i} onClick={() => colorSelect(v)}>{v.name}</Button>))
        return list
    }

    //第二个表单的尺码的选择
    const btnList2 = [
        { status: 0, name: 'L' },
        { status: 1, name: 'M' },
        { status: 2, name: 'S' },
    ]
    const [isTopBtn2, setIsTopBtn2] = useState(0)
    const clickTopBtn2 = (value) => {
        setIsTopBtn2(value)
    }
    const sizeSelect = (v) => {
        setSize1(v.name)
        return clickTopBtn2(v.status)
    }
    const btnListRender2 = (arr) => {
        let list = []
        arr.map((v, i) => list.push(<Button style={{ marginRight: '10px', width: '60px' }} type={v.status === isTopBtn2 ? 'primary' : 'default'} key={i} onClick={() => { sizeSelect(v) }}>{v.name}</Button>))
        return list
    }

    //第三个表单的日期选择器
    const onChange4 = (date, dateString) => {
        console.log(date, 111);
        console.log(dateString, 222);
        setTime(moment(dateString).format('YYYY-MM-DD'));
    };

    //提交表单
    const onFinish = () => {

        let arr = []
        fileList.forEach(v => {
            arr.push(v.response.fileName)
        })
        // console.log(arr);

        const form1Data = form1.getFieldsValue();
        const form2Data = form2.getFieldsValue();
        const form3Data = form3.getFieldsValue();
        // console.log(src);
        form1Data.picture = src
        delete form1Data.pictures
        form1Data.leftPic = arr[0]
        form1Data.centerPic = arr[1]
        form1Data.rightPic = arr[2]

        form2Data.color = color1;
        form2Data.size = size1;

        console.log(time, 2);
        if (form3Data.onTimeType === '1') {
            let time2 = moment(new Date()).format('YYYY-MM-DD');
            form3Data.onTime = time2;
            form3Data.onState = '2';
        } else if (form3Data.onTimeType === '2') {
            form3Data.onTime = time;
            form3Data.onState = '3';
        } else {
            form3Data.onTime = ''
            form3Data.onState = '3';
        }

        console.log(form1Data);
        console.log(form2Data);
        console.log(form3Data);

        let formData = { ...form1Data, ...form2Data, ...form3Data }
        console.log(formData);

        addGoods(formData).then((res) => {
            console.log(res);
            if (res.code === 200) {
                message.success('新增成功！');
                navigate('/home/goods')
            }
        })

    };

    return <div className='addGoodsMain'>
        <div className='addGoodsTop'>
            <div>
                <Breadcrumb>
                    <Breadcrumb.Item>商品管理</Breadcrumb.Item>
                    <Breadcrumb.Item>新增实物商品</Breadcrumb.Item>
                </Breadcrumb>
            </div>
            <h2>新增实物商品</h2>
        </div>
        <div className='addGoodsMiddle'>
            <p className='addGoodsMiddleItem1'>基础信息</p>
            <div className='addGoodsMiddleItem2'>
                <Form
                    labelCol={{
                        span: 2,
                    }}
                    wrapperCol={{
                        span: 8,
                    }}
                    name="basic"
                    form={form1}

                    autoComplete="off"
                    colon={false}
                >
                    <Form.Item
                        label="商品名称"
                        name="goodsName"
                        rules={[
                            {
                                required: true,
                                message: '请输入商品名称！',
                            },
                        ]}
                    >
                        <Input placeholder='请输入...' />
                    </Form.Item>

                    <Form.Item
                        label="商品封面"
                        name="picture"
                        rules={[
                            {
                                required: true,
                                message: '请上传图片!',
                            },
                        ]}
                        valuePropName="fileList"
                        getValueFromEvent={e => {
                            if (Array.isArray(e)) {
                                return e;
                            }
                            return e && e.fileList
                        }}
                    >
                        <Upload
                            name="file"
                            listType="picture-card"
                            className="avatar-uploader"
                            showUploadList={false}
                            action="http://192.168.221.234:8011/service_goods/fileUpload"
                            beforeUpload={beforeUpload}
                            onChange={handleChange}
                        >
                            {imageUrl ? (
                                <img
                                    src={imageUrl}
                                    alt="avatar"
                                    style={{
                                        width: '100%',
                                    }}
                                />
                            ) : (
                                uploadButton
                            )}
                        </Upload>

                    </Form.Item>

                    <Form.Item
                        label="商品轮播图"
                        name="pictures"
                        rules={[
                            {
                                required: true,
                                message: '请上传你的轮播图!',
                            },
                        ]}
                    >

                        <Upload
                            action="http://192.168.221.234:8011/service_goods/fileUpload"
                            listType="picture-card"
                            fileList={fileList}
                            onPreview={handlePreview}
                            onChange={handleChange2}
                        >
                            {fileList.length >= 3 ? null : uploadButton2}
                        </Upload>
                        <Modal visible={previewVisible} title={previewTitle} footer={null} onCancel={handleCancel}>
                            <img
                                alt="example"
                                style={{
                                    width: '100%',
                                }}
                                src={previewImage}
                            />
                        </Modal>
                    </Form.Item>

                    <Form.Item
                        label="商品类目"
                        name="classId"
                        rules={[
                            {
                                required: true,
                                message: '请选择课程类目!',
                            },
                        ]}
                    >
                        <Select>
                            {selectListRender(type)}
                        </Select>
                    </Form.Item>

                    <Form.Item
                        label="商品描述"
                        name="goodsDescribe"
                    >
                        <Input.TextArea placeholder="请输入..." />
                    </Form.Item>

                    <Form.Item
                        label="排序号"
                        name="sortingId"
                    >
                        <Input placeholder="请输入..." />
                    </Form.Item>
                </Form>
            </div>
        </div>
        <div className='addGoodsMiddle'>
            <p className='addGoodsMiddleItem1'>规格信息</p>
            <div className='addGoodsMiddleItem2'>
                <Form
                    labelCol={{
                        span: 2,
                    }}
                    wrapperCol={{
                        span: 10,
                    }}
                    name="basic2"
                    form={form2}

                    autoComplete="off"
                    colon={false}
                >
                    <Form.Item
                        label="颜色"
                        name="color"
                    >
                        {btnListRender(btnList)}
                    </Form.Item>

                    <Form.Item
                        label="尺码"
                        name="size"
                    >
                        {btnListRender2(btnList2)}
                    </Form.Item>

                    <Form.Item
                        label="价格"
                        name="price"
                    >
                        <Input addonAfter="元" />
                    </Form.Item>
                    <Form.Item
                        label="库存"
                        name="inventory"
                    >
                        <Input addonAfter="件" />
                    </Form.Item>

                </Form>
            </div>
        </div>
        <div className='addGoodsMiddle'>
            <p className='addGoodsMiddleItem1'>销售信息</p>
            <div className='addGoodsMiddleItem2'>
                <Form
                    labelCol={{
                        span: 2,
                    }}
                    wrapperCol={{
                        span: 8,
                    }}
                    form={form3}
                    name="basic3"

                    autoComplete="off"
                    colon={false}
                    initialValues={{
                        onTimeType: "1"
                    }}
                >
                    <Form.Item
                        label="商品最大价格"
                        name="maxPrice"
                        rules={[
                            {
                                required: true,
                                message: '请输入商品的最高价格!',
                            },
                        ]}
                    >
                        <Input addonAfter="元" />
                    </Form.Item>
                    <Form.Item
                        label="商品最低价格"
                        name="minPrice"
                        rules={[
                            {
                                required: true,
                                message: '请输入商品的最低价格!',
                            },
                        ]}
                    >
                        <Input addonAfter="元" />
                    </Form.Item>

                    <Form.Item
                        label="划线价格"
                        name="markPrice"
                    >
                        <Input addonAfter="元" />
                    </Form.Item>

                    <Form.Item
                        label="每人最多购买"
                        name="maxBuy"
                        rules={[
                            {
                                required: true,
                                message: '请输入每人最多购买商品的数量!',
                            },
                        ]}
                    >
                        <Input addonAfter="件" />
                    </Form.Item>
                    <Form.Item
                        label="每人最少购买"
                        name="minBuy"
                        rules={[
                            {
                                required: true,
                                message: '请输入每人最少购买商品的数量!!',
                            },
                        ]}
                    >
                        <Input addonAfter="件" />
                    </Form.Item>

                    <Form.Item
                        label="上架时间"
                        name="onTimeType"
                        rules={[
                            {
                                required: true,
                                message: '请选择上架时间!',
                            },
                        ]}
                    >
                        <Radio.Group name="radiogroup">
                            <Row style={{ marginBottom: '20px' }}>
                                <Col>
                                    <Radio value={'1'}>立即上架</Radio>
                                </Col>
                            </Row>
                            <Row style={{ marginBottom: '20px' }}>
                                <Col>
                                    <Radio value={'2'}>定时上架</Radio>
                                </Col>
                                <Col>
                                    <Space direction="vertical" size={12}>
                                        <DatePicker onChange={onChange4} />
                                    </Space>
                                </Col>
                            </Row>
                            <Row>
                                <Col>
                                    <Radio value={'3'}>暂不上架</Radio>
                                </Col>
                            </Row>
                        </Radio.Group>

                    </Form.Item>

                    <Form.Item
                        wrapperCol={{
                            offset: 2,
                        }}
                    >
                        <Button type="primary" onClick={onFinish}>
                            提交
                        </Button>
                        &nbsp;&nbsp;&nbsp;
                        <Button onClick={() => {
                            message.warning('取消新增！');
                            navigate('/home/goods')
                        }}>
                            返回
                        </Button>
                    </Form.Item>
                </Form>
            </div>
        </div>
    </div>
}
export default AddGoods;